package com.chunlin.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/request")
public class RequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //告诉浏览器,按照html的形式进行解析
        resp.setContentType("text/html");
        //调用req的各个方法,把得到的结果汇总到一个字符串上,统一返回网页上
        StringBuilder respBody = new StringBuilder();

        // 下列内容是在浏览器上按照 html 的方式来展示的. 此时 \n 在 html 中并不是换行
        // 而使用 <br> 标签表示换行
        respBody.append(req.getProtocol());
        respBody.append("<br>");
        respBody.append(req.getMethod());
        respBody.append("<br>");
        respBody.append(req.getRequestURI());
        respBody.append("<br>");
        //获取这个webapp的根路径,我们这里应该是hello-world
        respBody.append(req.getContextPath());
        respBody.append("<br>");
        respBody.append(req.getQueryString());
        respBody.append("<br>");

        //拼接Header
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String header = headerNames.nextElement();
            respBody.append(header + " : " + req.getHeader(header));
            respBody.append("<br>");
        }

        //统一返回结果
        resp.getWriter().write(respBody.toString());
    }
}
